package com.deruan.hotcore.resource.command;

import java.util.Date;

import javax.swing.JOptionPane;

import org.columba.api.command.ICommandReference;
import org.columba.api.command.IWorkerStatusController;
import org.columba.api.gui.frame.IFrameMediator;
import org.columba.core.command.Command;
import org.columba.core.command.CommandCancelledException;
import org.columba.core.command.StatusObservableImpl;
import org.columba.core.context.base.api.IStructureValue;
import org.columba.core.context.semantic.api.ISemanticContext;
import org.columba.core.gui.frame.FrameManager;
import org.columba.core.util.NameParser;
import org.columba.mail.folder.AbstractMessageFolder;
import org.columba.mail.folder.FolderInconsistentException;
import org.columba.mail.folder.IMailFolder;
import org.columba.mail.folder.IMailbox;
import org.columba.mail.folder.headercache.SyncHeaderList;
import org.columba.mail.gui.frame.MailFrameMediator;
import org.columba.mail.gui.frame.MessageViewOwner;
import org.columba.mail.gui.frame.TreeViewOwner;
import org.columba.mail.gui.message.IMessageController;
import org.columba.mail.util.MailResourceLoader;
import org.columba.ristretto.message.Address;
import org.columba.ristretto.message.Flags;

import com.deruan.hotcore.resource.gui.tree.ContactTreeNode;
import com.deruan.hotcore.resource.gui.tree.IResultTreeController;
import com.deruan.hotcore.resource.gui.tree.MessageSearchNode;
import com.deruan.hotcore.resource.gui.tree.ResourceTreeNode;
import com.deruan.hotcore.resource.gui.tree.ResultTreeNode;

public class ViewMessageResultCommand extends Command
{
    private IFrameMediator mediator;
	
	private boolean updateGui;
	
	private ResultTreeNode node;
	
	private IMailFolder relationFolder;
	
	private IMailbox srcFolder;
	
	private Object uid;
	
	private Flags flags;
	
	private IStructureValue value;

	private String subject;

	private String bodyText;

	private Date date;

	private NameParser.Name name;

	private Address from;
	
	public ViewMessageResultCommand(IFrameMediator mediator,
			ICommandReference reference) {
		super(reference);

		this.mediator = mediator;

		// Register as listener to the SelectionManger
		// to check for selection changes
		updateGui = true;

		priority = Command.REALTIME_PRIORITY;
	}

	
	public void updateGUI() throws Exception {

		// Update only if the selection did not change
		if (updateGui) {
			IMessageController messageController = ((MessageViewOwner) mediator)
			.getMessageController();
	        // display changes
	       messageController.updateGUI(); 
	       fillContext();
		}

	}

	/**
	 * @see org.columba.api.command.Command#execute(Worker)
	 */
	public void execute(IWorkerStatusController worker) throws Exception 
	{
		// Register as SelectionListener to track the selection
		// of the tree
		if (!updateGui)
			return;

		String name = null;
		
		ResultCommandReference r = (ResultCommandReference) getReference();

		node = (MessageSearchNode) r.getSelectedNode();
        //get selected folder
		srcFolder = ((MessageSearchNode)node).getFolder();

		// register for status events
		//((StatusObservableImpl) srcFolder.getObservable()).setWorker(wsc);
		// get selected message UID
		uid = ((MessageSearchNode)node).getMessageIdObject();

		if (!srcFolder.exists(uid)) {
			return;
		}

		try {
			// get flags
			flags = srcFolder.getFlags(uid);

			// get messagecontroller of frame
			IMessageController messageController = ((MessageViewOwner) mediator)
					.getMessageController();

			messageController.showMessage(srcFolder, uid);

			//restartMarkAsReadTimer(flags, messageController, r);

			// fill semantic context
			//prepareContextData();
		} catch (FolderInconsistentException e) {
			Object[] options = new String[] { MailResourceLoader.getString("",
					"global", "ok").replaceAll("&", ""), };
			int result = JOptionPane.showOptionDialog(FrameManager.getInstance()
					.getActiveFrame(), MailResourceLoader
					.getString("dialog", "error", "message_deleted"), "Error",
					JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null,
					null, null);

			if (result == JOptionPane.YES_OPTION) {
				// Synchronize the complete folder
				SyncHeaderList.sync((AbstractMessageFolder) srcFolder,
						srcFolder.getHeaderList());
			}

			throw new CommandCancelledException();
		}
	}
	
	private void fillContext() {
		if ( value == null) return;

		// create identity value
		IStructureValue identity = value.addChild(
				ISemanticContext.CONTEXT_NODE_IDENTITY,
				ISemanticContext.CONTEXT_NAMESPACE_CORE);
		if (name != null && name.toString() != null)
			identity.setString(ISemanticContext.CONTEXT_ATTR_DISPLAY_NAME,
					ISemanticContext.CONTEXT_NAMESPACE_CORE, name.toString());
		if (from != null && from.getMailAddress() != null)
			identity.setString(ISemanticContext.CONTEXT_ATTR_EMAIL_ADDRESS,
					ISemanticContext.CONTEXT_NAMESPACE_CORE, from
							.getMailAddress());
		if (name != null && name.getFirstName() != null)
			identity.setString(ISemanticContext.CONTEXT_ATTR_FIRST_NAME,
					ISemanticContext.CONTEXT_NAMESPACE_CORE, name
							.getFirstName());
		if (name != null && name.getLastName() != null)
			identity
					.setString(ISemanticContext.CONTEXT_ATTR_LAST_NAME,
							ISemanticContext.CONTEXT_NAMESPACE_CORE, name
									.getLastName());

		// create message value
		IStructureValue message = value.addChild(
				ISemanticContext.CONTEXT_NODE_MESSAGE,
				ISemanticContext.CONTEXT_NAMESPACE_CORE);
		if (subject != null)
			message.setString(ISemanticContext.CONTEXT_ATTR_SUBJECT,
					ISemanticContext.CONTEXT_NAMESPACE_CORE, subject);
		if (date != null)
			message.setDate(ISemanticContext.CONTEXT_ATTR_DATE,
					ISemanticContext.CONTEXT_NAMESPACE_CORE, date);

		IMessageController messageController = ((MessageViewOwner) mediator)
				.getMessageController();

		bodyText = messageController.getText();

		// @TODO: assert(bodyText != null) or if (bodyText != null)
		message.setString(ISemanticContext.CONTEXT_ATTR_BODY_TEXT,
				ISemanticContext.CONTEXT_NAMESPACE_CORE, bodyText);

		// set value
		mediator.getSemanticContext().setValue(value);
	}

}
